package hrhq.cntvcn.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import hrhq.cntvcn.mapper.HrhqVideoMapper;
import hrhq.cntvcn.pojo.HrhqVideo;
import hrhq.cntvcn.pojo.SearchResult;
import hrhq.cntvcn.service.SearchVideoService;
import hrhq.cntvcn.utils.SolrUtils;
@Service
public class SearchVideoServiceImpl implements SearchVideoService{
	private static Logger logger = Logger.getLogger(SearchVideoServiceImpl.class);
	private final static SolrClient solrClient =new SolrUtils().getZkSolrClient();
	@Autowired
	private HrhqVideoMapper videoMapper;

	@Override
	public void addIndexById(String... ids) {
		logger.info("执行添加索引操作");
		ArrayList<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		for (String id : ids) {
			HrhqVideo video = videoMapper.selectVideoById(id);
			SolrInputDocument document = new SolrInputDocument();
			document.addField("id", video.getId());
			document.addField("video_title", video.getTitle());
			document.addField("video_remark", video.getRemark());
			document.addField("video_name", video.getVideoName());
			document.addField("video_create_date", video.getCreateDate());
			document.addField("video_modify_date", video.getModifyDate());
			document.addField("video_click_num", video.getClickNum());
			document.addField("video_image", video.getVideoImage());
			document.addField("video_id", video.getVideoId());
			docs.add(document);
		}
		try {
			solrClient.add(docs);
			solrClient.commit();
			logger.info("添加索引成功");
		} catch (SolrServerException e) {
			logger.error("Add docs Exception !!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("Unknowned Exception!!!!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		}

		
	}


	public void deleteAllIndex() {
		logger.info("执行删除所有索引操作");
		try {
			solrClient.deleteByQuery("*:*");
			solrClient.commit();
			logger.info("删除索引成功");
		} catch (SolrServerException e) {
			logger.error("Delete Indexs Exception !!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("Unknowned Exception!!!!!\n" + e.getStackTrace() + "\n" + e.getCause());
			e.printStackTrace();
		}

	}

	public void deleteIndexByQuery(String query) throws SolrServerException, IOException {
		logger.info("执行删除索引操作");
		solrClient.deleteByQuery(query);
	}

	public SearchResult<HrhqVideo> searchByVideoTitle(String titleKey,Integer rows,Integer currPage) throws SolrServerException {
		logger.info("执行视频标题检索");
		// ApplicationContext context = new
		// ClassPathXmlApplicationContext("classpath:spring/applicationContext-*");
		// long start = System.currentTimeMillis();//测试时间11780ms
		// solrServer =(SolrServer) context.getBean("cloudSolrServer");
		// SearchResult<HrhqVideo> searchByKey = searchByKey("_title", titleKey,
		// null,true);
		// long end = System.currentTimeMillis();
		// System.out.println(end-start);
		return searchByKey("video_title", titleKey, null, true,rows,currPage);
	}

	public SearchResult<HrhqVideo> searchByVideoRemark(String remarkKey,Integer rows,Integer currPage) throws SolrServerException {
		logger.info("执行视频摘要检索");
		return searchByKey("video_remark", remarkKey, null, true,rows,currPage);
	}

	public SearchResult<HrhqVideo> searchByQuery(String DIYquery, Boolean isHighlight,Integer rows,Integer currPage) throws SolrServerException {
		logger.info("执行自定义检索");
		return searchByKey(null, null, DIYquery, isHighlight,rows,currPage);

	}

	public SearchResult<HrhqVideo> searchByKey(String searchParam, String keywords, String DIYquery,
			Boolean isHighlight,Integer rows,Integer currPage) throws SolrServerException {
		SolrQuery query = new SolrQuery();
		if (DIYquery != null) {
			query.setQuery(DIYquery);
		} else {
			query.setQuery(searchParam + ":" + keywords);
		}
		query.setStart((currPage-1)*rows);
		query.setRows(rows);
		if (isHighlight == true) {
			query.setHighlight(true);
			query.addHighlightField(searchParam);
			query.setHighlightSimplePre("<font color=\"red\">");
			query.setHighlightSimplePost("</font>");
		}
	
		QueryResponse queryResponse = null;
	
			try {
				queryResponse = solrClient.query(query);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		SolrDocumentList results = queryResponse.getResults();
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		SearchResult<HrhqVideo> searchResult = new SearchResult<HrhqVideo>();
		List<HrhqVideo> list = new ArrayList<>();
		for (SolrDocument doc : results) {
			HrhqVideo video = new HrhqVideo();
			// content.setId((String) doc.get("id"));
			if (searchParam.equals("video_title")) {
				video.setTitle(highlighting.get(doc.get("id")).get(searchParam).get(0));
			} else {
				video.setTitle((String) doc.get("video_title"));
			}
			// content.setTitle((String) doc.get("_title"));
			
			if (searchParam.equals("video_remark")) {
				video.setRemark(highlighting.get(doc.get("id")).get("searchParam").get(0));
			} else {
				video.setRemark((String) doc.get("video_remark"));
			}
			video.setUploadUrl((String) doc.get("video_image"));
			video.setVideoId((String) doc.get("video_id"));
			// System.out.println(list);
			list.add(video);
		}
		searchResult.setResultList(list);
		searchResult.setRecordCount(results.getNumFound());
		return searchResult;
	}


}
